import {
  Directive,
  ElementRef,
  Input,
  OnChanges,
  SimpleChanges,
} from '@angular/core';
import { makeLoadingIcon } from './loading-icon';

@Directive({
  selector: '[fuiLoading]',
})
export class LoadingDirective implements OnChanges {

  /** Loading state. */
  @Input() fuiLoading: boolean;

  /** Loading block height. */
  @Input() fuiLoadingHeight: string;

  constructor(private elementRef: ElementRef) {
    const hostPosition = this.elementRef.nativeElement.style.position;
    if (hostPosition !== 'absolute' || hostPosition !== 'relative') {
      this.elementRef.nativeElement.style.position = 'relative';
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    const {
      fuiLoading: loadingChanges,
    } = changes;

    if (loadingChanges) {
      if (loadingChanges.currentValue) {
        this.showLoading();
      } else {
        this.hideLoading();
      }
    }
  }

  showLoading() {
    // 创建loading svg icon
    const loadingIcon = makeLoadingIcon();

    // 创建icon的外部容器用于布局
    const container = document.createElement('div');
    container.classList.add('fui-loading-container');
    container.appendChild(loadingIcon);
    if (this.fuiLoadingHeight) {
      container.style.height = this.fuiLoadingHeight;
    }

    this.elementRef.nativeElement.appendChild(container);
    this.elementRef.nativeElement.classList.add('fui-loading-active');
  }

  hideLoading() {
    const container = this.elementRef.nativeElement.querySelector('.fui-loading-container');
    if (container) {
      this.elementRef.nativeElement.removeChild(container);
      this.elementRef.nativeElement.classList.remove('fui-loading-active');
    }
  }
}
